const fs = require('fs');

var orders = [];

function readOrder(target) {
    fs.readFile('./order.json', 'utf-8', (err, data) => {
        target = JSON.parse(data);
        console.log(target);
    });
}

function addOrder(k, v) {

    fs.readFile('./order.json', 'utf-8', (err, data) => {
        orders = JSON.parse(data);
        console.log('添加数据之前：')
        console.log(orders);
        var o = {
            gId: k,
            goodName: v.goodName,
            gPrice: v.gPrice
        }
        orders.push(o);
        fs.writeFile('./order.json', JSON.stringify(orders), err => {
            if (err) {
                throw err;
                return false
            }
            console.log('添加数据成功！');
        });
    });


    // fs.open('./order.json', 'a+', (err, fd)=>{
    //     if(err) {
    //         throw err;
    //         return false;
    //     }
    //     var o = {
    //         gId:k,
    //         goodName:v.goodName,
    //         gPrice: v.gPrice
    //     }
    //     fs.write(fd, JSON.stringify(o), (err, bytes, str)=>{
    //         if(err){
    //             fs.close(fd);
    //             throw err;
    //             return false
    //         }
    //         console.log('添加数据成功！共写入' + bytes + '字节。');
    //     });
    // });

}

function modifyOrder(k, v){

    fs.readFile('./order.json', 'utf-8', (err, data) => {
        orders = JSON.parse(data);
        console.log('修改数据之前：')
        console.log(orders);

        for(var d of orders){
            if(d.gId == k){
                d.goodName = v.goodName;
                d.gPrice = v.gPrice;
                break;
            }
        }

        fs.writeFile('./order.json', JSON.stringify(orders), err => {
            if (err) {
                throw err;
                return false
            }
            console.log('修改数据成功！');
        });
    });

}

function delOrder(k){

    fs.readFile('./order.json', 'utf-8', (err, data) => {
        orders = JSON.parse(data);
        console.log('删除数据之前：')
        console.log(orders);

        var pos = -1;
        for(var i=0; i<orders.length; i++){
            if(orders[i].gId == k) {
                pos = i; break;
            }
        }
        orders.splice(pos,1);

        fs.writeFile('./order.json', JSON.stringify(orders), err => {
            if (err) {
                throw err;
                return false
            }
            console.log('删除数据成功！');
        });
    });

}

// readOrder(orders);
// modifyOrder('003', {
//     goodName: '比亚迪海豹',
//     gPrice: 238888
// });
delOrder('003');
